import os
import re

class RegexFileRenamer:
    """
    使用正则表达式批量重命名文件
    """

    def __init__(self, folder_path, pattern, mode="remove"):
        """
        :param folder_path: 文件夹路径
        :param pattern: 正则表达式
        :param mode: 模式 "remove" 删除匹配部分, "keep" 只保留匹配部分
        """
        self.folder_path = folder_path
        self.pattern = pattern
        self.mode = mode.lower()
        self.regex = re.compile(pattern)

    def rename_file(self, filename):
        if self.mode == "remove":
            # 删除匹配部分
            new_filename = self.regex.sub("", filename)
        elif self.mode == "keep":
            # 只保留匹配部分
            match = self.regex.findall(filename)
            if match:
                # 拼接所有匹配片段作为新文件名
                new_filename = "_".join(match)
                # 保留原扩展名
                _, ext = os.path.splitext(filename)
                new_filename = new_filename + ext
            else:
                return None
        else:
            raise ValueError("模式错误: mode 只能是 'remove' 或 'keep'")
        return new_filename

    def process(self):
        for filename in os.listdir(self.folder_path):
            old_path = os.path.join(self.folder_path, filename)
            if not os.path.isfile(old_path):
                continue

            new_filename = self.rename_file(filename)
            if new_filename and new_filename != filename:
                new_path = os.path.join(self.folder_path, new_filename)
                os.rename(old_path, new_path)
                print(f"重命名: {filename} -> {new_filename}")


if __name__ == "__main__":
    folder = input("请输入文件夹路径: ").strip()
    pattern = input("请输入正则表达式: ").strip()
    mode = input("请选择模式（remove=删除匹配部分, keep=只保留匹配部分）: ").strip()

    renamer = RegexFileRenamer(folder, pattern, mode)
    renamer.process()
